<template>
  <div class="z-chart" ref="chart" :style="{ width, height }"></div>
</template>

<script>
import echarts from "@/plugins/echarts";

const { throttle, debounce } = require("throttle-debounce");

export default {
  name: "ZChart",
  props: {
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    resizable: {
      // 用来控制组件绘制图形时，是否随窗口大小变化 重新绘制
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      chart: null,
      resizeHandler: null, // 是一个函数
    };
  },
  methods: {
    setOption(option) {
      this.chart.setOption(option);
    },
    getOption() {
      return this.chart.getOption();
    },
    resize(option) {
      console.log("resize");
      return this.chart.resize(option); // 调用resize方法 会重新的以新的大小绘制图形
    },
  },
  mounted() {
    this.chart = echarts.init(this.$refs.chart);

    this.resizeHandler = throttle(400, () => this.resize());
    this.resizable && window.addEventListener("resize", this.resizeHandler);
  },
  activated() {
    this.resizable &&
      this.resizeHandler &&
      window.addEventListener("resize", this.resizeHandler);
  },
  deactivated() {
    window.addEventListener("resize", this.resizeHandler);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.resizeHandler);
  },
};
</script>

<style scoped></style>
